package com.gxlevi.bean

case class WebLogBeanCase(
                           valid: Boolean,
                           remote_addr: String,
                           remote_user: String,
                           time_local: String,
                           request: String,
                           status: String,
                           body_bytes_sent: String,
                           http_referer: String,
                           http_user_agent: String,
                           guid: String
                         )

class WebLogBean extends Serializable {

  var valid: Boolean = true
  var remote_addr: String = _
  var remote_user: String = _
  var time_local: String = _
  var request: String = _
  var status: String = _
  var body_bytes_sent: String = _
  var http_referer: String = _
  var http_user_agent: String = _
  var guid: String = _

  override def toString: String = {
    var sb = new StringBuilder
    sb.append(this.valid)
    sb.append("\001").append(this.valid)
    sb.append("\001").append(this.remote_addr)
    sb.append("\001").append(this.remote_user)
    sb.append("\001").append(this.time_local)
    sb.append("\001").append(this.request)
    sb.append("\001").append(this.status)
    sb.append("\001").append(this.body_bytes_sent)
    sb.append("\001").append(this.http_referer)
    sb.append("\001").append(this.http_user_agent)
    sb.append("\001").append(this.guid)
    sb.toString()
  }
}

object WebLogBean {
  def apply(line: String): WebLogBean = {
    val arr = line.split(" ")
    var webLogBean = new WebLogBean
    try {
      if (arr.length > 11) {
        webLogBean.guid = arr(0)
        webLogBean.remote_addr = arr(1)
        webLogBean.remote_user = arr(2)
        var time_local = arr(4) + " " + arr(5)
        if (null == time_local || "" == time_local) time_local = "-invalid_time-"
        webLogBean.time_local = time_local
        webLogBean.request = arr(7)
        webLogBean.status = arr(9)
        webLogBean.body_bytes_sent = arr(10)
        webLogBean.http_referer = arr(11)
        if (arr.length > 11) {
          val sb = new StringBuilder
          var i = 11
          while (i < arr.length) {
            sb.append(arr(i))
            i += 1
          }
          webLogBean.http_user_agent = sb.toString
        } else {
          webLogBean.http_user_agent = arr(11)
        }

        if (webLogBean.status.toInt >= 400) {
          webLogBean.valid = false
        }

        if ("-invalid_time-" == webLogBean.time_local) webLogBean.valid = false
      } else {
        webLogBean = null
      }
    } catch {
      case _ => webLogBean = null
    }

    webLogBean
  }
}